import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

/**
 * 应用状态管理
 */
export const useAppStore = defineStore('app', () => {
  // 状态
  const sidebarCollapsed = ref(false)
  const theme = ref<'light' | 'dark'>('light')
  const loading = ref(false)
  const breadcrumbs = ref<Array<{ label: string; to?: string }>>([])
  const notifications = ref<Array<{
    id: string
    type: 'success' | 'error' | 'warning' | 'info'
    title: string
    message: string
    duration?: number
    closable?: boolean
  }>>([])

  // 计算属性
  const isDark = computed(() => theme.value === 'dark')
  const hasNotifications = computed(() => notifications.value.length > 0)

  // 方法
  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
  }

  const setSidebarCollapsed = (collapsed: boolean) => {
    sidebarCollapsed.value = collapsed
  }

  const setTheme = (newTheme: 'light' | 'dark') => {
    theme.value = newTheme
    // 保存到本地存储（仅在客户端环境中）
    if (typeof window !== 'undefined' && window.localStorage) {
      localStorage.setItem('theme', newTheme)
    }
    // 更新HTML class
    if (newTheme === 'dark') {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }

  const toggleTheme = () => {
    setTheme(theme.value === 'light' ? 'dark' : 'light')
  }

  const setLoading = (value: boolean) => {
    loading.value = value
  }

  const setBreadcrumbs = (items: Array<{ label: string; to?: string }>) => {
    breadcrumbs.value = items
  }

  const addNotification = (notification: {
    type: 'success' | 'error' | 'warning' | 'info'
    title: string
    message: string
    duration?: number
    closable?: boolean
  }) => {
    const id = Date.now().toString()
    notifications.value.push({
      id,
      ...notification,
      duration: notification.duration ?? 3000,
      closable: notification.closable ?? true
    })

    // 自动移除通知
    if (notification.duration !== 0) {
      setTimeout(() => {
        removeNotification(id)
      }, notification.duration ?? 3000)
    }
  }

  const removeNotification = (id: string) => {
    const index = notifications.value.findIndex(n => n.id === id)
    if (index > -1) {
      notifications.value.splice(index, 1)
    }
  }

  const clearNotifications = () => {
    notifications.value = []
  }

  const showSuccess = (title: string, message?: string, duration?: number) => {
    addNotification({
      type: 'success',
      title,
      message: message || '',
      duration
    })
  }

  const showError = (title: string, message?: string, duration?: number) => {
    addNotification({
      type: 'error',
      title,
      message: message || '',
      duration
    })
  }

  const showWarning = (title: string, message?: string, duration?: number) => {
    addNotification({
      type: 'warning',
      title,
      message: message || '',
      duration
    })
  }

  const showInfo = (title: string, message?: string, duration?: number) => {
    addNotification({
      type: 'info',
      title,
      message: message || '',
      duration
    })
  }

  // 初始化主题
  const initTheme = () => {
    // 仅在客户端环境中访问localStorage
    let savedTheme: 'light' | 'dark' | null = null
    if (typeof window !== 'undefined' && window.localStorage) {
      savedTheme = localStorage.getItem('theme') as 'light' | 'dark' | null
    }
    
    const prefersDark = typeof window !== 'undefined' && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
    
    if (savedTheme) {
      setTheme(savedTheme)
    } else if (prefersDark) {
      setTheme('dark')
    } else {
      setTheme('light')
    }
  }

  return {
    // 状态
    sidebarCollapsed,
    theme,
    loading,
    breadcrumbs,
    notifications,
    
    // 计算属性
    isDark,
    hasNotifications,
    
    // 方法
    toggleSidebar,
    setSidebarCollapsed,
    setTheme,
    toggleTheme,
    setLoading,
    setBreadcrumbs,
    addNotification,
    removeNotification,
    clearNotifications,
    showSuccess,
    showError,
    showWarning,
    showInfo,
    initTheme
  }
})